package com.kedacom.emptyproject.view.activity

import android.app.Activity
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import com.kedacom.emptyproject.BR
import com.kedacom.emptyproject.R
import com.kedacom.emptyproject.adapter.ScheduleRecyclerAdapter
import com.kedacom.emptyproject.databinding.ActivityMainBinding
import com.kedacom.emptyproject.model.bean.ResultBean
import com.kedacom.emptyproject.model.bean.ScheduleItemInfo
import com.kedacom.emptyproject.model.bean.TaskColor
import com.kedacom.emptyproject.util.DateUtils
import com.kedacom.emptyproject.viewmodel.MainViewModel
import com.kedacom.util.DatetimeUtil
import com.kedacom.widget.pop.DateTimePickerDialog
import com.kedacom.widget.pop.listener.OnDateTimePickListener
import java.util.*


/**
 * 参考《昆山工作台项目》
 * @property mActivity Activity
 * @property scheduleItemAdapter ScheduleRecyclerAdapter?
 */
class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() {

    override fun getContentViewId() = R.layout.activity_main
    private lateinit var mActivity: Activity
    private var scheduleItemAdapter: ScheduleRecyclerAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mActivity = this
        initView()
    }

    private fun initView() {

        nViewDataBinding.llTaskCalendarDateSelect.setOnClickListener {
            showDateSelectedDialog()
        }

        // 初始年月
        var year: Int = Calendar.getInstance().get(Calendar.YEAR)
        var month: Int = Calendar.getInstance().get(Calendar.MONTH) + 1

        nViewDataBinding.tvTaskScheduleCalendarYear.text = year.toString()
        nViewDataBinding.tvTaskScheduleCalendarMonth.text = month.toString()


        scheduleItemAdapter =
            ScheduleRecyclerAdapter(
                R.layout.item_schedule_day,
                null,
                BR.itemScheduleBean
            )
        nViewDataBinding.rvItemSchedule.layoutManager = GridLayoutManager(context, 7)
        nViewDataBinding.rvItemSchedule.adapter = scheduleItemAdapter
        scheduleItemAdapter!!.data = converData(year, month, arrayListOf())

        nViewModel.scheduleList.observe(this) { list ->
            year = nViewDataBinding.tvTaskScheduleCalendarYear.text.toString().toInt()
            month = nViewDataBinding.tvTaskScheduleCalendarMonth.text.toString().toInt()
            if (list != null) {
                scheduleItemAdapter!!.data = converData(year, month, list)
            }
        }
    }

    /**
     * 将服务端返回值转换为我们需要的实体对象
     * @param year Int
     * @param month Int
     * @param list List<ResultBean>
     * @return ArrayList<ScheduleItemInfo>
     */
    private fun converData(
        year: Int,
        month: Int,
        list: List<ResultBean>
    ): ArrayList<ScheduleItemInfo> {
        val days: Array<IntArray> = DateUtils.getDayOfMonthFormat(year, month)//获取当前月份的日历分布

        return if (days[days.size - 1][0] < 25) {//最后一行的首位日期如果小于25，就不需要换行。
            val theDaysFive = IntArray(35)//5周
            dealData(theDaysFive, days, list)
        } else {
            val theDaysSix = IntArray(42)//6周
            dealData(theDaysSix, days, list)
        }
    }

    private fun dealData(
        targetDays: IntArray,
        sourceDays: Array<IntArray>,
        list: List<ResultBean>
    ): ArrayList<ScheduleItemInfo> {
        val dataList = arrayListOf<ScheduleItemInfo>()

        var dayNum = 0
        //将二维数组转化为一维数组，方便使用
        for (i in sourceDays.indices) {
            for (element in sourceDays[i]) {
                if (dayNum >= targetDays.size) {
                    break
                }
                targetDays[dayNum] = element
                dayNum++
            }
        }

        val year = nViewDataBinding.tvTaskScheduleCalendarYear.text.toString().toInt()
        val month = nViewDataBinding.tvTaskScheduleCalendarMonth.text.toString().toInt()
        val currentMonthDaysCount = DateUtils.getDaysOfMonth(year, month)
        var firstDayOfMonthIndex = -1
        for ((index, theDay) in targetDays.withIndex()) {
            val info = ScheduleItemInfo()
            for (bean in list) {
                var tempDate = bean.scheduleDate.substring(8)
                if (tempDate.startsWith("0")) {
                    tempDate = tempDate.substring(1)
                }
                if (tempDate == theDay.toString()) {
                    info.taskCount = 1
                    when (bean.color) {
                        "red" -> {
                            info.taskState = TaskColor.RED
                        }
                        "yellow" -> {
                            info.taskState = TaskColor.YELLOW
                        }
                        "blue" -> {
                            info.taskState = TaskColor.BLUE
                        }
                    }
                }
            }
            info.todayValue = theDay.toString()

            // 得到当月第一天的索引
            if ((index + 1) == DateUtils.getFirstDayWeekCurrentMonth(year, month)) {
                firstDayOfMonthIndex = index
            }

            if (firstDayOfMonthIndex >= 0
                && index >= 0
                && index >= firstDayOfMonthIndex
                && index < firstDayOfMonthIndex + currentMonthDaysCount
            ) {
                info.isCurrentMonthDay = true//标记为当月
                if (DatetimeUtil.getMonth() == month
                    && DatetimeUtil.getYear() == year
                    && (index + 1) == DateUtils.getCurrentDayOfMonth() + firstDayOfMonthIndex
                ) {
                    info.isToday = true// 标记为当日
                }
            }
            dataList.add(info)
        }
        return dataList
    }

    /**
     * 显示日期选择弹窗
     */
    private fun showDateSelectedDialog() {
        val dateTimePickerDialog: DateTimePickerDialog = DateTimePickerDialog.Builder()
            .title("选择时间")
            .optionsViewShowConfig(
                showYear = true, showMonth = true,
                showDay = false, showHour = false, showMinute = false
            )
            // 显示的时间单位名称，默认为 年 月 日，不显示"时"和"分"
            .onDateTimePickListener(object : OnDateTimePickListener {

                override fun onDateTimePick(date: Date) {
                    val calendar = Calendar.getInstance()
                    calendar.time = date
                    val year = calendar.get(Calendar.YEAR)
                    val month = calendar.get(Calendar.MONTH) + 1
                    nViewDataBinding.tvTaskScheduleCalendarYear.text = year.toString()
                    nViewDataBinding.tvTaskScheduleCalendarMonth.text = month.toString()
//                    showToast("选中的时间为" + DatetimeUtil.dateToLongStr(date))
                    // 调用接口查询选中年的月份用户每天的任务列表。
                    nViewModel.getScheduleTask(year, month)
//                    scheduleItemAdapter!!.data = getScheduleData(year, month, arrayListOf())
                }
            })
            .build()

        dateTimePickerDialog.show(this)
    }

}
